<template>
  <el-select
    v-model="tempOrgCode"
    remote
    filterable
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :remote-method="remoteOrgMethod"
    :loading="orgLoading"
    :size="size"
  >
    <el-option
      v-for="item in orgOptions"
      :key="item.orgCode"
      :label="item.orgName"
      :value="item.orgCode"
    />
  </el-select>
</template>

<script>
import { fetchOrgArray } from '@/api/base/common'

export default {
  name: 'OrgSelectComponent',
  props: {
    // 父组件传来的值
    placeholder: {
      type: String,
      default: '',
      require: false
    },
    disabled: {
      type: Boolean,
      default: false,
      require: false
    },
    clearable: {
      type: Boolean,
      default: false,
      require: false
    },
    value: {
      type: String,
      default: '',
      require: false
    },
    size: {
      type: String,
      default: '',
      require: false
    },
    orgType: {
      type: String,
      default: '1',
      require: false
    }
  },
  data() {
    return {
      currentEntityCode: '',
      orgOptions: [],
      orgLoading: false
    }
  },
  computed: {
    tempOrgCode: {
      get() {
        return this.currentEntityCode
      },
      set(newVal) {
        const oldVal = this.currentEntityCode
        this.currentEntityCode = newVal
        this.$emit('input', newVal)
        this.$emit('change', newVal, oldVal)
      }
    }
  },
  watch: {
    orgType: {
      immediate: true,
      handler(value) {
        this.remoteOrgMethod('')
      }
    },
    value: {
      immediate: true,
      handler(value) {
        if (this.currentEntityCode === value) {
          return
        }
        this.currentEntityCode = value
      }
    }
  },
  created() {
    this.remoteOrgMethod('')
  },
  methods: {
    remoteOrgMethod(query) {
      query = query == null ? '' : query.trim()
      this.orgLoading = true
      fetchOrgArray({ query: query, orgType: this.orgType }).then((response) => {
        this.orgOptions = response.data
        this.orgLoading = false
      }, (response) => {
        this.orgLoading = false
      })
    }
  }
}
</script>
